package com.example.handheld4_gsignal_app.services;

import android.content.Context;
import android.util.Log;
import com.example.handheld4_gsignal_app.data.SignalRecord;
import com.example.handheld4_gsignal_app.network.ApiClient;
import com.example.handheld4_gsignal_app.data.models.SignalCollectionResponse;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 历史服务类 - 处理历史记录相关功能
 */
public class HistoryService {
    
    private static final String TAG = "HistoryService";
    
    private Context context;
    private List<SignalRecord> signalRecords;
    private ApiClient apiClient;

    public HistoryService(Context context) {
        this.context = context;
        this.signalRecords = new ArrayList<>();
        this.apiClient = ApiClient.getInstance(context);
    }

    /**
     * 获取所有记录
     */
    public List<SignalRecord> getAllRecords() {
        return new ArrayList<>(signalRecords);
    }

    /**
     * 获取今天的记录
     */
    public List<SignalRecord> getTodayRecords() {
        List<SignalRecord> todayRecords = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String today = sdf.format(new Date());
        
        for (SignalRecord record : signalRecords) {
            if (record.getCollectedAt().startsWith(today)) {
                todayRecords.add(record);
            }
        }
        return todayRecords;
    }

    /**
     * 获取本周的记录
     */
    public List<SignalRecord> getWeekRecords() {
        List<SignalRecord> weekRecords = new ArrayList<>();
        long weekAgo = System.currentTimeMillis() - 7 * 24 * 3600000L;
        
        for (SignalRecord record : signalRecords) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                Date recordDate = sdf.parse(record.getCollectedAt());
                if (recordDate != null && recordDate.getTime() >= weekAgo) {
                    weekRecords.add(record);
                }
            } catch (Exception e) {
                // 忽略解析错误
            }
        }
        return weekRecords;
    }

    /**
     * 获取本月的记录
     */
    public List<SignalRecord> getMonthRecords() {
        List<SignalRecord> monthRecords = new ArrayList<>();
        long monthAgo = System.currentTimeMillis() - 30 * 24 * 3600000L;
        
        for (SignalRecord record : signalRecords) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                Date recordDate = sdf.parse(record.getCollectedAt());
                if (recordDate != null && recordDate.getTime() >= monthAgo) {
                    monthRecords.add(record);
                }
            } catch (Exception e) {
                // 忽略解析错误
            }
        }
        return monthRecords;
    }

    /**
     * 添加新记录
     */
    public void addRecord(SignalRecord record) {
        record.setId(signalRecords.size() + 1);
        signalRecords.add(0, record); // 添加到列表开头
    }

    /**
     * 删除记录
     */
    public boolean deleteRecord(int recordId) {
        for (int i = 0; i < signalRecords.size(); i++) {
            if (signalRecords.get(i).getId() == recordId) {
                signalRecords.remove(i);
                return true;
            }
        }
        return false;
    }

    /**
     * 清空所有记录
     */
    public void clearAllRecords() {
        signalRecords.clear();
    }

    /**
     * 获取记录总数
     */
    public int getRecordCount() {
        return signalRecords.size();
    }

    /**
     * 从服务器获取历史数据
     */
    public void fetchHistoryDataFromServer(String deviceId, String startTime, String endTime, 
                                         int limit, int offset, HistoryCallback callback) {
        // 构建请求URL
        String endpoint = null;

        if(startTime != null && endTime != null) {
            endpoint = String.format("/api/signals?device_id=%s&start_time=%s&end_time=%s&limit=%d&offset=%d",
                    deviceId, startTime, endTime, limit, offset);
        }
        else  {
            endpoint = String.format("/api/signals?device_id=%s&limit=%d&offset=%d",
                    deviceId, limit, offset);
        }
        
        apiClient.get(endpoint, new ApiClient.ApiCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    // 解析响应数据
                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<SignalCollectionResponse>>(){}.getType();
                    List<SignalCollectionResponse> responses = gson.fromJson(response, listType);
                    
                    // 转换为SignalRecord格式
                    List<SignalRecord> records = new ArrayList<>();
                    for (SignalCollectionResponse responseItem : responses) {
                        SignalRecord record = convertToSignalRecord(responseItem);
                        records.add(record);
                    }
                    
                    // 更新本地数据
                    signalRecords.clear();
                    signalRecords.addAll(records);
                    
                    if (callback != null) {
                        callback.onSuccess(records);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "解析服务器响应失败", e);
                    if (callback != null) {
                        callback.onError("解析响应失败: " + e.getMessage());
                    }
                }
            }
            
            @Override
            public void onError(String error) {
                if (callback != null) {
                    callback.onError(error);
                }
            }
        });
    }

    /**
     * 将API响应转换为SignalRecord
     */
    private SignalRecord convertToSignalRecord(SignalCollectionResponse response) {
        SignalRecord record = new SignalRecord();
        record.setId(response.getId());
        record.setDeviceId(response.getDeviceId());
        record.setSignalStrength(response.getSignalStrength());
        record.setLatitude(response.getLatitude());
        record.setLongitude(response.getLongitude());
        record.setAltitude(response.getAltitude());
        record.setAccuracy(response.getAccuracy().floatValue());
        record.setNetworkType(response.getNetworkType());
        record.setOperatorName(response.getOperatorName());
        record.setCellId(response.getCellId());
        record.setLac(response.getLac());
        record.setMcc(response.getMcc());
        record.setMnc(response.getMnc());
        record.setRsrp(response.getRsrp());
        record.setRsrq(response.getRsrq());
        record.setRssi(response.getRssi());
        record.setSnr(response.getSnr());
        record.setCollectedAt(response.getCollectedAt());
        return record;
    }

    /**
     * 历史数据回调接口
     */
    public interface HistoryCallback {
        void onSuccess(List<SignalRecord> records);
        void onError(String error);
    }
}